// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 * Creator: yanking
 * Create time: 2022-02-27 15:20
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.Greedy;

public class MaxProfit {
    // 返回买卖股票的最大利润
    public int maxProfit(int[] prices) {
        // 在股票价格最低点购买，在股票价格最高点出售股票
        int sum = 0;
        int buy = -1, pre = 0, p = 1;
        while (p < prices.length) {
            // 选择购买股票时机
            if (prices[p] > prices[pre] && buy < 0) {
                // 股票处于涨价阶段，直接进行购买
                buy = prices[pre];
            }
            // 选择出售股票时机
            if (prices[p] < prices[pre] && buy >= 0) {
                // 股票开始降价，直接出售
                sum += prices[pre] - buy;
                buy = -1; // 股票价格存在0
            }
            if (prices[p] >= prices[pre] && p == prices.length - 1 && buy >= 0) {
                sum += prices[p] - buy;
            }
            ++p;
            ++pre;
        }

        return sum;
    }
}
